<template>
  <div class="project-sidebar">
    <div class="search-container">
      <el-input
        v-model="searchText"
        placeholder="搜索项目"
        prefix-icon="el-icon-search"
        clearable
        @clear="searchText = ''">
      </el-input>
    </div>

  <div class="button-group">
      <el-button 
        type="primary" 
        icon="el-icon-plus" 
        @click="showAddDialog = true"
        class="action-button">
        新建项目
      </el-button>
      
      <el-button 
        type="success" 
        icon="el-icon-download" 
        @click="exportData"
        class="action-button">
        导出数据
      </el-button>

       <el-upload
        action=""
        :show-file-list="false"
        :before-upload="beforeImport"
        accept=".json"
        class="action-button"
      >
        <el-button type="warning" icon="el-icon-upload2" class="full-width-btn">
          导入数据
        </el-button>
      </el-upload>
    </div>

    <el-scrollbar class="project-list-container">
      <el-menu
        :default-active="activeIndex"
        @select="handleSelect"
        class="custom-menu">
        <el-menu-item 
          v-for="project in filteredProjects" 
          :key="project.id" 
          :index="project.id"
          class="project-item">
          <i class="el-icon-folder"></i>
          <span class="project-name">{{ project.name }}</span>
          
          <el-dropdown 
            trigger="click" 
            @command="handleProjectCommand($event, project.id)"
            class="project-actions">
            <span class="el-dropdown-link">
              <i class="el-icon-more"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="rename">重命名</el-dropdown-item>
              <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
    </el-scrollbar>

    <!-- 新建项目对话框 -->
    <el-dialog 
      title="新建项目" 
      :visible.sync="showAddDialog" 
      width="400px"
      :close-on-click-modal="false">
      <el-form @submit.native.prevent="addProject">
        <el-form-item label="项目名称">
          <el-input 
            v-model="newProjectName" 
            placeholder="请输入项目名称"
            autofocus
            maxlength="50"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="addProject"
          :disabled="!newProjectName.trim()">
          确定
        </el-button>
      </span>
    </el-dialog>

    <!-- 重命名对话框 -->
    <el-dialog
      title="重命名项目"
      :visible.sync="showRenameDialog"
      width="400px"
      :close-on-click-modal="false">
      <el-form @submit.native.prevent="confirmRename">
        <el-form-item label="新名称">
          <el-input
            v-model="renameText"
            autofocus
            maxlength="50"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="showRenameDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmRename"
          :disabled="!renameText.trim()">
          确认
        </el-button>
      </span>
    </el-dialog>

     <!-- 导入确认对话框 -->
    <el-dialog
      title="导入确认"
      :visible.sync="showImportDialog"
      width="500px"
      :close-on-click-modal="false">
      <div v-if="importDataPreview">
        <p>将导入以下数据：</p>
        <ul>
          <li v-for="store in Object.keys(importDataPreview.data)" :key="store">
            {{ store }}: {{ importDataPreview.data[store].length }} 条记录
          </li>
        </ul>
        <el-alert type="warning" :closable="false" style="margin-top: 15px;">
          注意：导入将覆盖现有数据！
        </el-alert>
      </div>
      <span slot="footer">
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmImport"
          :loading="importing">
          确认导入
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import idb from '@/utils/idb';

export default {
  data() {
    return {
      projects: [],
      searchText: '',
      activeIndex: '',
      showAddDialog: false,
      showRenameDialog: false,
      newProjectName: '',
      renameText: '',
      currentProjectId: null
    }
  },
  computed: {
    filteredProjects() {
      return this.projects.filter(p => 
        p.name.toLowerCase().includes(this.searchText.toLowerCase())
      ).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    }
  },
  created() {
    this.loadProjects();
  },
  methods: {
    async loadProjects() {
      try {
        this.projects = await idb.getAll('projects') || [];
      } catch (error) {
        console.error('加载项目失败:', error);
        this.$message.error('加载项目失败');
      }
    },
    
    handleSelect(index) {
      this.activeIndex = index;
      const project = this.projects.find(p => p.id === index);
      this.$emit('select-project', project);
    },
    
    async addProject() {
      if (!this.newProjectName.trim()) return;
      
      try {
        const newProject = {
          id: `proj_${Date.now()}`,
          name: this.newProjectName.trim(),
          createdAt: new Date().toISOString()
        };
        
        await idb.add('projects', newProject);
        this.projects.unshift(newProject);
        this.$message.success('项目创建成功');
        this.showAddDialog = false;
        this.newProjectName = '';
        
        // 自动选中新建的项目
        this.$nextTick(() => {
          this.handleSelect(newProject.id);
        });
      } catch (error) {
        console.error('添加项目失败:', error);
        this.$message.error('项目创建失败');
      }
    },
    
    handleProjectCommand(command, projectId) {
      if (command === 'delete') {
        this.deleteProject(projectId);
      } else if (command === 'rename') {
        this.prepareRename(projectId);
      }
    },
    
    prepareRename(projectId) {
      const project = this.projects.find(p => p.id === projectId);
      if (project) {
        this.currentProjectId = projectId;
        this.renameText = project.name;
        this.showRenameDialog = true;
      }
    },
    
    async confirmRename() {
      if (!this.renameText.trim() || !this.currentProjectId) return;
      
      try {
        const project = this.projects.find(p => p.id === this.currentProjectId);
        if (project) {
          project.name = this.renameText.trim();
          await idb.update('projects', project);
          this.$message.success('重命名成功');
          this.showRenameDialog = false;
          
          // 如果当前选中该项目，更新选中状态
          if (this.activeIndex === this.currentProjectId) {
            this.$emit('select-project', project);
          }
        }
      } catch (error) {
        console.error('重命名失败:', error);
        this.$message.error('重命名失败');
      }
    },
    
    async deleteProject(projectId) {
      try {
        await this.$confirm('确定删除该项目吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await idb.delete('projects', projectId);
        this.projects = this.projects.filter(p => p.id !== projectId);
        this.$message.success('项目已删除');
        
        // 如果删除的是当前选中的项目，清空选中状态
        if (this.activeIndex === projectId) {
          this.activeIndex = '';
          this.$emit('select-project', null);
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          this.$message.error('删除项目失败');
        }
      }
    },
    
    async exportData() {
      try {
        this.$message.info('正在导出数据...');
        await idb.exportAndDownload(`project_backup_${new Date().toISOString().slice(0,10)}.json`);
        this.$message.success('数据导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('数据导出失败');
      }
    },
     // 导入前验证
    beforeImport(file) {
      this.importFile = file;
      const reader = new FileReader();
      
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result);
          if (!data.databaseName || !data.data) {
            throw new Error('无效的数据格式');
          }
          this.importDataPreview = data;
          this.showImportDialog = true;
        } catch (error) {
          this.$message.error('文件解析失败: ' + error.message);
        }
      };
      
      reader.onerror = () => {
        this.$message.error('文件读取失败');
      };
      
      reader.readAsText(file);
      return false; // 阻止自动上传
    },

    // 确认导入
    async confirmImport() {
      if (!this.importDataPreview) return;
      
      this.importing = true;
      try {
        // 清空现有数据
        const storeNames = Object.keys(this.importDataPreview.data);
        await this.clearStores(storeNames);
        
        // 导入新数据
        for (const storeName of storeNames) {
          const items = this.importDataPreview.data[storeName] || [];
          if (items.length > 0) {
            await idb.addBulk(storeName, items);
          }
        }
        
        this.$message.success(`成功导入 ${storeNames.length} 个存储的数据`);
        this.showImportDialog = false;
        this.loadProjects(); // 重新加载项目列表
      } catch (error) {
        console.error('导入失败:', error);
        this.$message.error('数据导入失败: ' + error.message);
      } finally {
        this.importing = false;
      }
    },

    // 清空指定存储
    async clearStores(storeNames) {
      for (const storeName of storeNames) {
        try {
          await idb.clearStore(storeName);
        } catch (error) {
          console.warn(`清空存储 ${storeName} 失败:`, error);
        }
      }
    }
  
  }
}
</script>

<style scoped>
.project-sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  border-right: 1px solid #e8e8e8;
  box-shadow: 1px 0 4px rgba(0, 0, 0, 0.05);
}

.search-container {
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 0 16px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.action-button {
  width: 100%;
  height: 36px;
  margin: 0;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.action-button:hover {
  transform: translateY(-1px);
}

.action-button i {
  margin-right: 6px;
  font-size: 14px;
}

.project-list-container {
  flex: 1;
  overflow: hidden;
  padding: 8px 0;
}

.custom-menu {
  border-right: none;
  background-color: transparent;
}

.project-item {
  position: relative;
  height: 42px;
  line-height: 42px;
  display: flex;
  align-items: center;
  margin: 0 8px;
  border-radius: 4px;
  transition: all 0.2s;
}

.project-item:hover {
  background-color: #f5f7fa;
}

.project-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
  font-size: 13px;
  color: #333;
}

.project-actions {
  position: absolute;
  right: 8px;
  color: #c0c4cc;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.project-actions:hover {
  background-color: #e6e9f0;
  color: #606266;
}

.el-icon-folder {
  margin-right: 8px;
  color: #5a8dee;
  font-size: 16px;
}

.el-menu-item.is-active {
  background-color: #f0f7ff !important;
  color: #5a8dee !important;
  font-weight: 500;
}

.el-menu-item.is-active .project-name {
  color: #5a8dee;
}

.el-menu-item.is-active .el-icon-folder {
  color: #5a8dee;
}

.el-scrollbar__wrap {
  overflow-x: hidden;
  padding-bottom: 20px;
}

/* 对话框标题样式 */
.el-dialog__header {
  border-bottom: 1px solid #eee;
  padding: 15px 20px;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 500;
}

/* 导入列表样式 */
.import-preview-list {
  max-height: 300px;
  overflow-y: auto;
  margin: 10px 0;
  padding: 0;
  list-style: none;
}

.import-preview-list li {
  padding: 8px 12px;
  border-bottom: 1px dashed #eee;
  display: flex;
  justify-content: space-between;
}

.import-preview-list li:last-child {
  border-bottom: none;
}
</style>